package com.qdy.api;

import com.alibaba.fastjson.JSONObject;
import com.jiai.core.tools.RestResultGenerator;
import com.jiai.exception.ServiceException;
import com.jiai.weixin.util.WeiXinUtil;
import com.qdy.entity.user.SignIn;
import com.qdy.entity.user.User;
import com.qdy.entity.user.UserExtends;
import com.qdy.repository.SignInRepository;
import com.qdy.repository.UserExtendsRepository;
import com.qdy.repository.UserRepository;
import com.qdy.service.UserService;
import com.qdy.util.HttpUtil;
import com.qdy.util.geo.GeoHash;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.Calendar;
import java.util.Date;

/**
 * 用户API接口
 * @version  v1
 * Created by 方礼爱 on 2017/3/26.
 */
@RequestMapping(value = "/api/v1/user")
@RestController
public class UserAPIController {
    private static final Logger log= LoggerFactory.getLogger(UserAPIController.class);
    private static final String AppSecret="d6f45640810fbfbe3079bcb58ab12494";
    private static final String appId="wxf669876309ce1505";

    @Autowired
    private UserService userService;
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private UserExtendsRepository userExtendsRepository;

    @Autowired
    private SignInRepository signInRepository;

    /**
     * 微信小程序登录接口 如果已注册的用户则直接返回用户信息
     * @param code
     * @return
     */
    @RequestMapping(value = "/checkUser/{code}",method = RequestMethod.GET,produces = {"application/json;charset=UTF-8"})
    public Object checkUser(@PathVariable("code") String code)throws ServiceException{
        try {
           /*JSONObject object= WeiXinUtil.getAppSessionKey(appId,AppSecret,code);
            String openId=object.getString("openid");*/
            String openId="oMXPs0Kj2KNK5efSnYcFlhulIfjwdss";
           return RestResultGenerator.genSuccessResult(userService.getUserViewByOpenId(openId)) ;
        }catch (Exception e){
            throw new ServiceException("注册失败",e.getMessage());
        }
    }

    @RequestMapping(value="/register/{code}",method = RequestMethod.POST,produces = {"application/json;charset=UTF-8"})
    public Object register(User user, @PathVariable("code") String code)throws ServiceException{
        try{
            JSONObject object= WeiXinUtil.getAppSessionKey(appId,AppSecret,code);
            String openId=object.getString("openid");
            log.info("opeId:{}",openId);
            user.setOpenId(openId);
            userRepository.save(user);
            return RestResultGenerator.genSuccessResult(userService.getUserViewByOpenId(openId));
        }catch (Exception e){
            throw new ServiceException("注册失败",e.getMessage());
        }
    }

    /*
     * 用户实名注册
     * Author Zjyyy
     * */
    @RequestMapping(value="/authentication",method = RequestMethod.POST,produces = {"application/json;charset=UTF-8"})
    public Object authentication(UserExtends userExtends) throws ServiceException{
        try {
            userExtends.setStatus(1);
            userExtends.setUserId(HttpUtil.getUserId());
            userExtendsRepository.save(userExtends);
            return RestResultGenerator.genSuccessResult();
        } catch (Exception e) {
            throw new ServiceException("验证失败",e.getMessage());
        }
    }
    /**
     * 用户签到
     * @param signIn
     * @return
     */
    @RequestMapping(value="/singIn",method = RequestMethod.POST,produces = {"application/json;charset=UTF-8"})
    public Object singIn(SignIn signIn)throws  ServiceException{
        try{
            GeoHash geoHash=new GeoHash(Double.valueOf(signIn.getLatitude()),Double.valueOf(signIn.getLongitude()));
            Date startTime=new Date();
            Calendar Cal=java.util.Calendar.getInstance();
            Cal.setTime(startTime);
            Cal.add(java.util.Calendar.MINUTE,signIn.getMinute());
            signIn.setGeohash(geoHash.getGeoHashBase32());
            signIn.setStartTime(new Date());
            signIn.setEndTime(Cal.getTime());
            signIn.setUserId(HttpUtil.getUserId());
            signInRepository.save(signIn);
            return RestResultGenerator.genSuccessResult("签到成功!");
        }catch (Exception e){
            throw new ServiceException("签到失败",e.getMessage());
        }
    }

}
